package com.luhuiguo.cms.server.util;

import java.util.Arrays;

import org.apache.commons.lang.time.StopWatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Aspect
public class LoggingAspect {

    @SuppressWarnings("unused")
    @Pointcut("execution(* *..handler.*Handler.execute(..))")
    private void needLog() {
    };

    @Around("needLog()")
    public Object doLog(ProceedingJoinPoint pjp) throws Throwable {

        Logger logger = LoggerFactory.getLogger(pjp.getTarget().getClass());

        StopWatch sw = new StopWatch();
        if (logger.isInfoEnabled()) {

            logger
                    .info(
                            "\n----------------------------------------------------------------\n开始调用：{}.{}\n调用参数：{}\n----------------------------------------------------------------\n",
                            new Object[]{ pjp.getTarget().getClass().getName(), pjp.getSignature().getName(),
                                    Arrays.toString(pjp.getArgs()) });
            sw.start();
        }

        Object retVal = pjp.proceed();
        if (logger.isInfoEnabled()) {
            sw.stop();
            logger
                    .info(
                            "\n----------------------------------------------------------------\n结束调用 ：{}.{}\n调用参数：{}\n返回值：{}\n用时：{} 毫秒\n----------------------------------------------------------------\n",
                            new Object[]{ pjp.getTarget().getClass().getName(), pjp.getSignature().getName(),
                                    Arrays.toString(pjp.getArgs()), retVal, sw.getTime() });
        }
        return retVal;
    }

}
